#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
清理不兼容的扩展和缓存文件
这个脚本会清理项目中可能存在的不兼容文件和缓存
"""

import os
import shutil
import glob
import sys
from pathlib import Path

def clean_python_cache():
    """清理Python缓存文件"""
    print("🧹 清理Python缓存文件...")
    
    # 清理 __pycache__ 目录
    pycache_dirs = glob.glob("**/__pycache__", recursive=True)
    for cache_dir in pycache_dirs:
        if os.path.exists(cache_dir):
            shutil.rmtree(cache_dir)
            print(f"✓ 删除缓存目录: {cache_dir}")
    
    # 清理 .pyc 文件
    pyc_files = glob.glob("**/*.pyc", recursive=True)
    for pyc_file in pyc_files:
        if os.path.exists(pyc_file):
            os.remove(pyc_file)
            print(f"✓ 删除编译文件: {pyc_file}")
    
    # 清理 .pyo 文件
    pyo_files = glob.glob("**/*.pyo", recursive=True)
    for pyo_file in pyo_files:
        if os.path.exists(pyo_file):
            os.remove(pyo_file)
            print(f"✓ 删除优化文件: {pyo_file}")

def clean_temporary_files():
    """清理临时文件"""
    print("🧹 清理临时文件...")
    
    temp_patterns = [
        "*.tmp",
        "*.temp", 
        "*.bak",
        "*.swp",
        "*.~*",
        ".DS_Store",
        "Thumbs.db"
    ]
    
    for pattern in temp_patterns:
        temp_files = glob.glob(f"**/{pattern}", recursive=True)
        for temp_file in temp_files:
            if os.path.exists(temp_file):
                os.remove(temp_file)
                print(f"✓ 删除临时文件: {temp_file}")

def clean_log_files():
    """清理旧的日志文件"""
    print("🧹 清理旧的日志文件...")
    
    log_patterns = [
        "*.log",
        "*.log.*"
    ]
    
    for pattern in log_patterns:
        log_files = glob.glob(pattern)
        for log_file in log_files:
            if os.path.exists(log_file) and os.path.getsize(log_file) > 10 * 1024 * 1024:  # 大于10MB
                os.remove(log_file)
                print(f"✓ 删除大日志文件: {log_file}")

def clean_build_artifacts():
    """清理构建产物"""
    print("🧹 清理构建产物...")
    
    build_dirs = [
        "build/",
        "dist/",
        "*.egg-info/"
    ]
    
    for pattern in build_dirs:
        build_paths = glob.glob(pattern)
        for build_path in build_paths:
            if os.path.exists(build_path):
                if os.path.isdir(build_path):
                    shutil.rmtree(build_path)
                    print(f"✓ 删除构建目录: {build_path}")
                else:
                    os.remove(build_path)
                    print(f"✓ 删除构建文件: {build_path}")

def check_incompatible_packages():
    """检查不兼容的包"""
    print("🔍 检查不兼容的包...")
    
    try:
        import pkg_resources
        
        # 已知与Python 3.13有问题的包
        problematic_packages = [
            'numpy<1.24.0',
            'pandas<1.5.0',
            'scipy<1.9.0',
            'tensorflow<2.11.0'
        ]
        
        installed_packages = [d.project_name for d in pkg_resources.working_set]
        
        for package_spec in problematic_packages:
            package_name = package_spec.split('<')[0]
            if package_name in installed_packages:
                print(f"⚠️  发现可能不兼容的包: {package_name}")
                
    except ImportError:
        print("⚠️  无法检查包兼容性，pkg_resources不可用")

def fix_encoding_issues():
    """修复编码问题"""
    print("🔧 检查编码问题...")
    
    # 设置环境变量确保UTF-8编码
    os.environ['PYTHONIOENCODING'] = 'utf-8'
    os.environ['PYTHONLEGACYWINDOWSFSENCODING'] = '0'
    
    print("✓ 设置Python UTF-8编码环境变量")

def main():
    """主函数"""
    print("🚀 开始清理不兼容的扩展和缓存文件...")
    print(f"📁 当前工作目录: {os.getcwd()}")
    print(f"🐍 Python版本: {sys.version}")
    print("-" * 50)
    
    try:
        # 执行清理操作
        clean_python_cache()
        clean_temporary_files()
        clean_log_files()
        clean_build_artifacts()
        check_incompatible_packages()
        fix_encoding_issues()
        
        print("-" * 50)
        print("✅ 清理完成!")
        print("\n建议接下来执行:")
        print("1. pip check  # 检查依赖完整性")
        print("2. python main.py --port 8005  # 测试应用启动")
        
    except Exception as e:
        print(f"❌ 清理过程中出现错误: {e}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)